package com.ddw.meedeeuh.shared.movie.scrapers;

import java.io.File;
import java.util.regex.Matcher;

import com.ddw.meedeeuh.shared.io.SourceFile;
import com.ddw.meedeeuh.shared.movie.MovieSettings;

/**
 * Represents a utilities class for movie files
 * @author cmcnicholas
 *
 */
public abstract class MovieFileUtils {

	/**
	 * Method to extract a movie name from a source file
	 * @param file the file to extract the name from
	 * @param settings the movie settings settings
	 * @return a matched name or null
	 */
	public static String extractMovieName(SourceFile file, MovieSettings settings) {
		if(file == null) {
			throw new IllegalArgumentException("The source file cannot be null");
		}
		if(settings == null) {
			throw new IllegalArgumentException("The movie settings cannot be null");
		}

		// Get the name source
		final File nameSource = getNameSource(file, settings);

		// Check that the name source is valid
		if(nameSource == null) {
			throw new RuntimeException("The name source cannot be null");
		}

		// Match the name against the pattern and check it returned a result
		final Matcher matcher = settings.getNameRegex().matcher(nameSource.getName());
		if(matcher.find() == false) {
			return null;
		}

		return matcher.group().trim();
	}

	/**
	 * Method to extract a movie year from a source file
	 * @param file the file to extract the year from
	 * @param settings the movie settings settings
	 * @return a matched year or null
	 */
	public static Integer extractMovieYear(SourceFile file, MovieSettings settings) {
		if(file == null) {
			throw new IllegalArgumentException("The source file cannot be null");
		}
		if(settings == null) {
			throw new IllegalArgumentException("The movie settings cannot be null");
		}

		// Get the name source
		final File nameSource = getNameSource(file, settings);

		// Check that the name source is valid
		if(nameSource == null) {
			throw new RuntimeException("The name source cannot be null");
		}

		// Match the year against the pattern and check it returned a result
		final Matcher matcher = settings.getYearRegex().matcher(nameSource.getName());
		if(matcher.find() == false) {
			return null;
		}

		// Try to parse the value
		try {
			return Integer.parseInt(matcher.group().trim());
		} catch(NumberFormatException e) {
			return null;
		}
	}

	/**
	 * Gets the file instance to return the name source for,
	 * this will be the source for which the regex tries to
	 * match a movie name and year for
	 * @param file the file to find the source for
	 * @param settings the movie settings
	 * @return a file instance or null
	 */
	private static File getNameSource(SourceFile file, MovieSettings settings) {
		if(settings.matchNameOnParentFolder()) {
			return file.getInstance().getParentFile();
		} else {
			return file.getInstance();
		}
	}

}
